package com.tongji.seller.view.popup
{
	import com.tongji.seller.events.AddImageEvent;
	import com.tongji.seller.events.AddStoreItemEvent;
	import com.tongji.seller.events.UpdateItemImageEvent;
	import com.tongji.seller.events.utilsEvent.BubblesEvent;
	import com.tongji.seller.model.StoreProductModel;
	import com.tongji.seller.model.UserModel;
	import com.tongji.seller.utils.ConstVariableInventory;
	import com.tongji.seller.utils.Matting;
	import com.tongji.seller.vo.Picture;
	
	import flash.display.Bitmap;
	import flash.display.BitmapData;
	import flash.display.Loader;
	import flash.errors.IllegalOperationError;
	import flash.events.Event;
	import flash.events.MouseEvent;
	import flash.net.FileFilter;
	import flash.net.FileReference;
	import flash.utils.ByteArray;
	
	import flashx.textLayout.tlf_internal;
	
	import mx.binding.utils.BindingUtils;
	import mx.collections.ArrayCollection;
	import mx.controls.Alert;
	import mx.events.CloseEvent;
	import mx.graphics.codec.PNGEncoder;
	import mx.managers.PopUpManager;
	import mx.utils.Base64Encoder;
	
	import org.robotlegs.mvcs.Mediator;
	
	/**
	 *
	 * @author caddy
	 * @date 2011-12-13
	 */
	public class AddImageTitlwWinMediator extends Mediator
	{
		[Inject]
		public var view:AddImageTitleWindow;
		
		[Inject]
		public var userModel:UserModel;
		
		[Inject]
		public var productModel:StoreProductModel;
		[Bindable]
		public var readyArray:ArrayCollection = new ArrayCollection();//暂时存放所选择的图片
		private var loader:Loader;
		private var picture:Picture;
		private var imgList:Array;
		private var file:FileReference = new FileReference();
		private var imagesFilter:FileFilter = new FileFilter("图像文件(*.jpg,*.gif,*.png)", "*.jpg;*.gif;*.png");
		
		override public function onRegister():void
		{
			/*BindingUtils.bindProperty(view.savedImageList, "dataProvider", productModel, "imageList");*/
			BindingUtils.bindProperty(view.imgsList, "dataProvider", productModel, "imageList");

			eventMap.mapListener(view, CloseEvent.CLOSE, closeHandler, CloseEvent);
			eventMap.mapListener(view.saveImage, MouseEvent.CLICK, saveImagesHandler, MouseEvent);
			//eventMap.mapListener(view.browsebutton, MouseEvent.CLICK, browseFileHandler, MouseEvent);
			view.imgsList.addEventListener(BubblesEvent.DELETE_UPLOAD_IMAGE, deleteImageHandler);
			view.imgsList.addEventListener(BubblesEvent.ADD_IMAGE, addImageHandler);
			
			addContextListener(AddImageEvent.UPDATE_PNG_IMG, test, AddImageEvent);
		}
		
		private function test(event:AddImageEvent):void
		{
			// TODO Auto Generated method stub
			/*var imges:Array = new Array();
			for each(var obj:Object in productModel.imageList)
			{
				if (obj.edited == 1 && obj.newurl == null)
				{
					var str:String = obj.url;
					var strarr:Array = str.split("http://img.rryjw.com");
					imges.push(strarr[1]);
				}
			}
			for each(var img:Object in event.images)
			{
				imges.push(img);
			}
			dispatch(new UpdateItemImageEvent(UpdateItemImageEvent.UPDATE_IMAGE, productModel.currentProduct.ItemImgList.iId, imges));*/
		}
		
		protected function addImageHandler(event:BubblesEvent):void
		{
			switch(event.object.id)
			{
				case 1:
					productModel.imageList.getItemAt(0).newurl = event.object.image;
					break;
				case 2:
					productModel.imageList.getItemAt(1).newurl = event.object.image;
					break;
				case 3:
					productModel.imageList.getItemAt(2).newurl = event.object.image;
					break;
			}
		}
		
		/**
		 * 弹出默认的系统选择框 
		 * @param event
		 * 
		 */		
		protected function browseFileHandler(event:MouseEvent):void
		{
			imgList = new Array();
			file = new FileReference();
			try
			{
				file.browse([imagesFilter]);	
			}
			catch(illegalOperation:IllegalOperationError)
			{
			}
			file.addEventListener(Event.SELECT, onSelectFile);
		}
		
		/**
		 *选择欲上传的图片 
		 * @param event
		 * 
		 */		
		private function onSelectFile(event:Event):void
		{
			if (file.size > ConstVariableInventory.UPLOAD_MAX_SIZE)
				Alert.show("您的照片容量已经超过2M了，请压缩后重新上传！");
			else
			{				
				file.load();
				file.addEventListener(Event.COMPLETE, completeHandler);
				file.removeEventListener(Event.SELECT, onSelectFile);
			}					
		}
		
		
		private function completeHandler(event:Event):void
		{
			loader = new Loader();
			loader.loadBytes(file.data);
			loader.contentLoaderInfo.addEventListener(Event.COMPLETE, loaderCompleteHandler);	
			file.removeEventListener(Event.COMPLETE, completeHandler);				
		}
		
		private function loaderCompleteHandler(event:Event):void
		{
			if (event.target.width > 1700 || event.target.height > 1500)
			{
				Alert.show("您的照片尺寸太大了，建议改为700*500，然后再重新上传！");
			}
			else
			{
				/*if (readyArray.length >= 3)
					Alert.show("对不起，您已经不能再上传了。");
				else
					readyArray.addItem(loader.content);*/
				if (productModel.imageList.length >= 3)
					Alert.show("对不起，您已经不能再上传了。");
				else
					productModel.imageList.addItem(loader.content);
				/* img.source = loader.content;
				var bitmap:Bitmap = Bitmap(loader.content);
				
				var bitmapdata:BitmapData = Matting.mattingStart(bitmap);
				var prePic:BitmapData = bitmapdata;
				var encoder:mx.graphics.codec.PNGEncoder = new mx.graphics.codec.PNGEncoder();
				var byte:ByteArray = encoder.encode(bitmapdata);
				var Base64:Base64Encoder = new Base64Encoder();
				Base64.encodeBytes(byte);
				var image:String = Base64.toString();
				imgList.push(image);
				var object:Object = new Object();
				object.imgs = imgList;
				dispatchEvent(new BubblesEvent(BubblesEvent.ADD_LOCAL_IMAGE, object)); */
			}
		}		
		
		protected function deleteImageHandler(event:BubblesEvent):void
		{
			switch(event.object.id)
			{
				case 1:
					productModel.imageList.getItemAt(0).edited = 0;
					productModel.imageList.getItemAt(0).newurl = null;
					productModel.imageList.getItemAt(0).url = "assets/images/image.png";
					break;
				case 2:
					productModel.imageList.getItemAt(1).edited = 0;
					productModel.imageList.getItemAt(1).newurl = null;
					productModel.imageList.getItemAt(1).url = "assets/images/image.png";
					break;
				case 3:
					productModel.imageList.getItemAt(2).edited = 0;
					productModel.imageList.getItemAt(2).newurl = null;
					productModel.imageList.getItemAt(2).url = "assets/images/image.png";
					break;
			}
			productModel.imageList.refresh();
		}
		
		private function saveImagesHandler(event:MouseEvent):void
		{
			readyArray;
			var imgList:Array = new Array();
			if (productModel.imageState == 0)
			{
				for (var i:int = 0; i < productModel.imageList.length; i++)
				{
					var obj:Object = productModel.imageList.getItemAt(i);
					if (obj.edited == 0 && obj.newurl != null)
					{
						imgList.push(obj.newurl);
					}
				}			
			}
			else
			{
				for (var a:int = 0; a < productModel.imageList.length; a++)
				{
					var obj2:Object = productModel.imageList.getItemAt(a);
					if (obj2.newurl != null)
					{
						imgList.push(obj2.newurl);
					}
				}	
			}
			/*for (var i:int = 0; i < productModel.imageList.length; i++)
			{
				var obj:Object = productModel.imageList.getItemAt(i);
				if (obj.edited == 0 && obj.newurl != null)
				{
					imgList.push(obj.newurl);
				}
			}*/
			/*for each(var bitmap:Bitmap in productModel.imageList)
			{
				
			}	*/	
			if (productModel.imageState == 0)
			{
				dispatch(new AddStoreItemEvent(AddStoreItemEvent.ADD_STORE_ITEM, userModel.currentUserID, productModel.currentProduct.pid, imgList));
			}
			else
			{
				dispatch(new AddImageEvent(AddImageEvent.ADD_PNG_IMG, new ArrayCollection(imgList)));
			}
			PopUpManager.removePopUp(view);
		}
		
		private function closeHandler(event:Event):void
		{
			PopUpManager.removePopUp(view);
		}
	}
}